<?php 
/**
 * 登录相关服务类
 * @author haiqin
 *
 */
namespace Users\Service;
class LoginService{
	
	private $user;
	private $sms;
	
	public function __construct() {
		$this->user = D('Users');
	}
	
	/**
	 * 登录执行
	 * @param string $user
	 * @param string $pwd
	 */
	public function login($user,$pwd,$remember){
		$map = array(
			'username|mobile|email'=>$user,
			//'role' => array('like','%|ROLE_USER|%')
		);
		$info = $this->user->where($map)->find();
		if($info){
			if($info['password'] === $pwd){
				$this->createusersession($info);
				if($remember){
					cookie('member_username',$user,time()+3600*24*365);
					cookie('member_pwd',$pwd,time()+3600*24*365);
				}
				
				//增加登录日志
				$userslog = new \Userslog\Service\LogService();
				$userslog->addLog($info['uid'],'login','登录系统');
				
				return 1;//登录成功
			}else{
				return -1;//密码不正确
			}
		}else{
			return -2;//用户名或手机不存在
		}
	}
	
	//创建会员登录session
	public function createusersession($info){
		$userinfo['uid'] = $info['uid'];
		$userinfo['username'] = $info['username'];
		session('loginUser',$userinfo);
	}
	
	/**
	 * 注册添加用户
	 * @param unknown $appid
	 * @param unknown $user
	 * @param unknown $pwd
	 */
	public function add($user,$pwd,$mobile,$role){
		$data = array(
			'username' => $user,
			'password' => $pwd,
			'mobile' => $mobile,
			'role' => $role,
			'create_time'=> Date('Y-m-d H:i:s'),
			'update_time'=> Date('Y-m-d H:i:s'),
		);
		if($this->user->add($data)){
			$ret = $this->login($user, $pwd,1);
			if($ret == 1){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	
	
	public function cookielogin(){
		//判断是否有cookie信息自动登录
		if(!session('loginUser')){
			if(cookie('member_username') && cookie('member_pwd')){
				$u = $this->login(cookie('username'),cookie('pwd'),1);
				if($u == 1){
					redirect('/');
					exit();
				}
			}
		}else{
			redirect('/');
			exit();
		}
	}
}
?>